package com.example.mybatisdemo1.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * mybatis工具类
 *
 * @author 25688
 **/

public class MybatisUtil {

    private static SqlSession sqlSession;

    public static SqlSession createSession() throws IOException {
        //初始化工厂建造者
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //将核心配置文件转换成为input Stream流
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //通过SqlSessionFactoryBuilder建造sqlSessionFactory
        SqlSessionFactory factory = builder.build(inputStream);
        // 通过SqlSessionFactory生产出SqlSession对象 --- 会话，在完成操作后，必须释放， true添加数据时自动提交
        sqlSession = factory.openSession(true
        );
        return sqlSession;
    }
}
